/*
 *    Copyright 2009 Daniel Hayes
 *    This file is part of PreCT.
 *
 *    PreCT is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    PreCT is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with PreCT.  If not, see <http://www.gnu.org/licenses/>
 */

function Utils(){
}

Utils.prototype.setStageController = function(controller){
	this.stageController = controller;
}

/* Convert milliseconds into human readable time */
Utils.prototype.milsToTime = function(mils){
    var A = mils;
    var h = Math.floor((A / (1000 * 60 * 60)) % 24);
    var m = Math.floor((A / (1000 * 60)) % 60);
    var s = Math.floor((A / 1000) % 60);
    var hs = Math.floor(A / 10 % 100);
    
    var timeString = '';
    var includeRest = false;
    if (h > 0) {
        timeString = h + ':';
        includeRest = true;
    }
    
    if (includeRest || m > 0) {
        if (includeRest && m < 10) {
            timeString += '0';
        }
        timeString += m + ':';
        includeRest = true;
    }
    
    if (includeRest && s < 10) {
        timeString += '0';
    }
    
    timeString += s + "."
    if (hs == 0) {
        timeString += '00';
    }
    else 
        if (hs < 10) {
            timeString += '0' + hs;
        }
        else {
            timeString += hs;
        }
    
    return timeString;
}

Utils.prototype.calculateWeightedAverage = function(times){
	if(times.length < 12){
		return null;
	}
	
	var sum = 0;
	for(var i = 0; i < times.length; i++){
		sum += times[i];
	}
	
	return (sum - Math.max.apply(Math, times) - Math.min.apply(Math, times))/10;
}

Utils.prototype.calculateBestWeightedAverage = function(times){
	if(times.length < 12){
		return null;
	}
	
	var best = null;
	for(var i = 0; i <= times.length-12; i++){
		var avg = this.calculateWeightedAverage(times.slice(i,i+12));
		if(best == null || avg < best){
			best = avg;
		}
	}
	
	return best;
}

/* Disable screen timeout */
Utils.prototype.disableScreenBlank = function(){
    this.stageController.setWindowProperties({
        blockScreenTimeout: true
    });
}

/* Enable screen timeout */
Utils.prototype.enableScreenBlank = function(){
    this.stageController.setWindowProperties({
        blockScreenTimeout: false
    });	
}
